#!/usr/bin/env bash

# ----------------------------------------------------------------------------
# Colors

RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[0;33m'
PLAIN='\033[0m'

RED_BOLD='\033[1;31m'
GREEN_BOLD='\033[1;32m'
BLUE_BOLD='\033[1;34m'
YELLOW_BOLD='\033[1;33m'
PLAIN_BOLD='\033[1;37m'

# ----------------------------------------------------------------------------
# Utilities

trap ctrl_c INT
ctrl_c() {
    tput cnorm
    exit
}

spinner() {
    local spin="\\|/-"
    local i=0
    tput civis
    while kill -0 "$1" 2>/dev/null; do
        i=$(( (i+1) %4 ))
        printf "\b%s" "${spin:$i:1}"
        sleep 0.07
    done
    tput cnorm
}

yesno() {
    while true; do
        printf "${BLUE}"
        printf " • $1 "

        if [[ $2 == "no" ]]; then
            printf "${PLAIN}[yes | ${GREEN_BOLD}no${PLAIN}] "
            read ans
            if [[ -z "$ans" ]]; then
                ans="no"
            fi
        else
            printf "${PLAIN}[${GREEN_BOLD}yes${PLAIN} | no] "
            read ans
            if [[ -z "$ans" ]]; then
                ans="yes"
            fi
        fi

        if [[ $ans == "yes" ]] || [[ $ans == "y" ]]; then
            return 0
        elif [[ $ans == "no" ]] || [[ $ans == "n" ]]; then
            return 1
        else
            printf "   ${RED}Invalid answer. Please answer with 'yes' or 'no'."
        fi
    done
}

ask() {
    printf "${PLAIN} • ${BLUE}$2 "

    printf "${PLAIN}[${GREEN_BOLD}$3${PLAIN}] "

    read ans
    if [[ -z "$ans" ]]; then
        ans="$3"
    fi

    eval "$1='"$ans"'"
}

command_exists () {
    type "$1" &> /dev/null
}

system_verify() {
    if ! command_exists $1; then
        printf "${PLAIN} • ${RED}$1 missing.${PLAIN} "

        if command_exists apt-get || command_exists yum || command_exists dnf; then
            printf "Installing...  "

            if command_exists dnf && [[ "$3" != "-" ]]; then
                sudo dnf install -y "$3"  > /dev/null 2>&1 &
                spinner $!
                printf "\b${GREEN}Installed!"

            elif command_exists yum && [[ "$3" != "-" ]]; then
                sudo yum install -y "$3"  > /dev/null 2>&1 &
                spinner $!
                printf "\b${GREEN}Installed!"

            elif command_exists apt-get && [[ "$2" != "-" ]]; then
                sudo apt-get install -y "$2"  > /dev/null 2>&1 &
                spinner $!
                printf "\b${GREEN}Installed!"

            else
                printf "${RED}Package doesn't exist for your arch. Please install it manually."
            fi

        else
            printf "Please install it manually."
        fi
    else
        printf "${PLAIN} • ${GREEN}$1 exists!${PLAIN}"
    fi
    printf "\n"
}

npm_verify() {
    if ! command_exists $1; then
        printf "${PLAIN} • ${RED}$1 missing.${PLAIN} "

        if command_exists npm; then
            printf "Installing...  "

            sudo npm install -g "$2"  > /dev/null 2>&1 &
            spinner $!

            printf "\b${GREEN}Installed!"
        else
            printf "Please install it manually using npm."
        fi
    else
        printf "${PLAIN} • ${GREEN}$1 exists!${PLAIN}"
    fi
    printf "\n"
}

pip_verify() {
    if ! command_exists $1; then
        printf "${PLAIN} • ${RED}$1 missing.${PLAIN} "

        if command_exists pip; then
            printf "Installing...  "

            sudo pip install "$2"  > /dev/null 2>&1 &
            spinner $!

            printf "\b${GREEN}Installed!"
        else
            printf "Please install it manually using pip."
        fi
    else
        printf "${PLAIN} • ${GREEN}$1 exists!${PLAIN}"
    fi
    printf "\n"
}

setup_autocomplete() {

    #Create auto complete file
cat > $CLIMATE_COMPLETION << EOF
        if [[ ! -z "\$ZSH_VERSION" ]]
        then
            autoload compinit
            autoload bashcompinit
            compinit
            bashcompinit
        fi

        _climate() 
        {
            local cur prev opts
            COMPREPLY=()
            cur="\${COMP_WORDS[COMP_CWORD]}"
            prev="\${COMP_WORDS[COMP_CWORD-1]}"
            opts=\$(cat $CLIMATE_SRC 2>/dev/null |\
                grep -P 'shelp\s"[^"]+"\s*"[^"]+"' |\
                cut -d"\"" -f2 |\
                cut -d" " -f1)

            if [[ ! -z "\$opts" ]] && [[ "\$prev" = "$CLIMATE_EXEC" ]]
            then
                COMPREPLY=( \$(compgen -W "\${opts}" -- \${cur}) )
            fi
        }
        complete -F _climate climate
EOF
	
    #Setup bash
    bashrc=$(eval echo "~$(logname)")/.bashrc
    if [[ -f "$bashrc" ]]; then
        if ! grep -Fxq "source $CLIMATE_COMPLETION" $bashrc
        then
            printf "\nsource %s" $CLIMATE_COMPLETION >> $bashrc
            source $CLIMATE_COMPLETION
        fi
    fi

    #Setup ZSH
    zshrc=$(eval echo "~$(logname)")/.zshrc
    if [[ -f "$zshrc" ]]; then
        if ! grep -Fxq "source $CLIMATE_COMPLETION" $zshrc
        then
            printf "\nsource %s" $CLIMATE_COMPLETION >> $zshrc
            source $CLIMATE_COMPLETION
        fi
    fi
}

main() {
    INSTALL_DIR=/usr/local/bin
    if [[ ! -z "$1" ]]; then
        INSTALL_DIR="$1"
    fi

    if [[ ! -w "$INSTALL_DIR" ]]; then
        printf "${RED_BOLD}Error: must be root to install.${PLAIN}\n"
        exit
    fi

    printf "${RED_BOLD}"
    printf "┌───────────────────┐\n"
    printf "│ "
    printf "${PLAIN_BOLD}"
    printf "climate installer "
    printf "${RED_BOLD}"
    printf "│\n"
    printf "└───────────────────┘\n"

    if [[ ! -f "climate" ]]; then
        printf "Downloading...  "
        system_verify "git" "git-all" "git-all"
        git clone https://github.com/adtac/climate.git --depth=1 > /dev/null 2>&1 &
        spinner $!
        cd climate
    fi

    CUR_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

    printf "\n${PLAIN}Alright, let's get started with a few questions. Just press enter if you want to use the ${GREEN_BOLD}default value.\n\n"

    printf "   ${RED}RED "
    printf "${GREEN}GREEN "
    printf "${BLUE}BLUE "
    printf "${YELLOW}YELLOW "
    printf "${PLAIN}PLAIN\n"
    USE_COLORS=false
    if yesno "The above text is colored. Do you want to enable colors in climate?"; then
        USE_COLORS=true
    fi
    printf "\n"

    SHOW_COMMAND=false
    if yesno "Show commands before execution?"; then
        SHOW_COMMAND=true
    fi
    printf "\n"

    ask EDITOR "What's your favourite editor?" "vi"

    CLIMATE_EXEC="climate"
    CLIMATE_SRC=$INSTALL_DIR/$CLIMATE_EXEC
    printf "#!/usr/bin/env bash\n\n" > $CLIMATE_SRC
    printf "USE_COLORS=${USE_COLORS}\n" >> $CLIMATE_SRC
    printf "SHOW_COMMAND=${SHOW_COMMAND}\n" >> $CLIMATE_SRC
    printf "EDITOR=${EDITOR}\n" >> $CLIMATE_SRC
    printf "\n" >> $CLIMATE_SRC
    tail -n +3 "$CUR_DIR/climate" >> $CLIMATE_SRC
    chmod +x $CLIMATE_SRC

    #Creates the auto-completion file
    CLIMATE_COMPLETION="/etc/bash_completion.d/climate_completion"
    setup_autocomplete

    printf "\nGreat. Now, let's check if you have the all requirements:\n\n"

    #             command           Debian based    RPM based
    system_verify "upower"          "upower"        "upower"
    system_verify "curl"            "curl"          "curl"
    system_verify "rar"             "rar"           "-"
    system_verify "unzip"           "unzip"         "unzip"
    system_verify "7z"              "p7zip-full"    "p7zip"
    system_verify "xdg-screensaver" "xdg-utils"     "xdg-open"
    system_verify "dig"             "dnsutils"      "bind-utils"
    system_verify "git"             "git-all"       "git-all"
    system_verify "python"          "python"        "python"
    system_verify "pip"             "python-pip"    "python-pip"
    system_verify "node"            "nodejs-legacy" "nodejs"
    system_verify "npm"             "npm"           "npm"
    system_verify "fdupes"          "fdupes"        "fdupes"
    system_verify "glances"         "glances"       "glances"
    system_verify "sensors"         "lm-sensors"    "lm_sensors"
    system_verify "sshfs"           "sshfs"         "fuse-sshfs"
    system_verify "gawk"            "gawk"          "gawk"
    system_verify "jq"              "jq"            "jq"

    npm_verify "http-server"   "http-server"
    npm_verify "is-up"         "is-up-cli"
    npm_verify "is-online"     "is-online-cli"

    pip_verify "speedtest"     "speedtest-cli"
    pip_verify "httpstat"      "httpstat"

    printf "\nNeat! You're all set. Run 'climate' to see the whole list "
    printf "of commands supported. Enjoy!${PLAIN}\n"
}

main $@
